package department

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"io/ioutil"
	"net/http"
)

func init() {
	server.Post("/api/Department/Add", AddDept, "添加部门", server.ManageBackend)
	server.Post("/api/Department/Edit", EditDept, "更新部门",server.ManageBackend)
	server.Post("/api/Department/Delete", DeleteDept, "删除部门", server.ManageBackend)
	server.Get("/api/Department/List", ListDept, "获取部门列表", server.ManageBackend)

}

// 添加部门
func AddDept(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, int64(100<<20))
	s, _ := ioutil.ReadAll(r.Body)
	dept := &model.Department{}
	err := helper.FromJSON(s, dept)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	// 校验字段
	err = helper.GetValidator().Struct(dept)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	duModel := base.GenerateDataUserModel(dept, r)
	deptService := NewDepartmentService()
	err = deptService.Save(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Add successfully").WithData(bson.M{
		"deptId": dept.GetId(),
	}))
}

// 更新部门
func EditDept(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, int64(100<<20))
	s, _ := ioutil.ReadAll(r.Body)
	dept := &model.Department{}
	err := helper.FromJSON(s, dept)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	// 校验字段
	err = helper.GetValidator().Struct(dept)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	if dept.ID.IsZero() {
		_, _ = helper.WriteJSON(w, server.Fail("deptID is required"))
		return
	}

	duModel := base.GenerateDataUserModel(dept, r)
	deptService := NewDepartmentService()
	err = deptService.Update(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Add successfully!"))
}

func DeleteDept(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(r.FormValue("deptId"))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	db, err := server.Mongo()
	if err != nil {
		helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	filter := bson.M{
		"ParentID": id.Hex(),
	}
	result := bson.M{}
	find, _ :=db.FindOne(server.DepartmentCollectionName,filter,&result)
	if find {
		_, _ = helper.WriteJSON(w, server.Fail("删除失败，存在下级部门"))
		return
	}

	filter2 := bson.M{
		"Depts": bson.M{
			"$regex":id.Hex(),
			"$options": "$i",
		},
		"$or": bson.A{
			bson.M{
				"isDeleted": 0,
			},
			bson.M{
				"isDeleted": nil,
			},
		},
	}
	find2, _ :=db.FindOne(server.UserCollectionName,filter2,&result)
	if find2 {
		_, _ = helper.WriteJSON(w, server.Fail("删除失败，部门下存在用户"))
		return
	}

	dept := &model.Department{
		ID: id,
	}
	duModel := base.GenerateDataUserModel(dept, r)
	deptService := NewDepartmentService()
	err = deptService.Remove(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}

func ListDept(w http.ResponseWriter, r *http.Request) {
	dept := &model.Department{}
	duModel := base.GenerateDataUserModel(dept, r)
	deptService := NewDepartmentService()
	results, err := deptService.List(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Get successfully!").WithData(results))
}
